package com.boyue.service.impl;

import com.boyue.dao.SysMenuDao;
import com.boyue.dao.impl.SysMenuDaoImpl;
import com.boyue.entity.SysMenu;
import com.boyue.service.SysMenuService;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @auth wzy
 * @date 2023/9/8 15:06
 */
public class SysMenuServiceImpl implements SysMenuService {

    private SysMenuDao sysMenuDao = new SysMenuDaoImpl();

    @Override
    public List<SysMenu> treeMenu() {
        try {

            List<SysMenu> menuList = sysMenuDao.list();

            // 遍历 parentid 为0
            List<SysMenu> topMenuList = menuList.stream()
                    .filter(menu -> menu.getParentId() == 0).collect(Collectors.toList());

            // 遍历 顶层菜单，加子菜单
            topMenuList.forEach(topMenu ->{
                addChildrenMenu(topMenu,menuList);
            });

            return topMenuList;

        }catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 为父菜单找子菜单
     * @param parentMenu 父菜单
     * @param menuList 菜单集合
     */
    private void addChildrenMenu(SysMenu parentMenu, List<SysMenu> menuList) {

        List<SysMenu> childrenMenu = menuList.stream().filter(menu -> menu.getParentId() == parentMenu.getMenuId()).collect(Collectors.toList());
        parentMenu.setChildren(childrenMenu);

        // 给子菜单 添加 孙菜单
        childrenMenu.forEach(topMenu ->{
            addChildrenMenu(topMenu,menuList);
        });
    }
}
